package com.svo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

//magnet:?xt=urn:btih:bb71630da5c5aa4d1b4f9371fcd1d2853a54725f
public class HttpUtils {
	
	public static String getForZip(String urlStr) {
		StringBuilder sb = new StringBuilder("");
		InputStream is;
		try {
			URL url = new URL(urlStr);
			is = url.openStream();
			GZIPInputStream gis = new GZIPInputStream(is);
			Scanner scanner = new Scanner(gis);
			while (scanner.hasNextLine()) {
				sb.append(scanner.nextLine());
			}
			scanner.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static String get(String urlStr, String cookie) {
		StringBuilder sb = new StringBuilder("");
		InputStream is;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//			conn.setRequestProperty("Cookie", cookie);
			is = conn.getInputStream();
			Scanner scanner = new Scanner(is);
			while (scanner.hasNextLine()) {
				sb.append(scanner.nextLine());
			}
			scanner.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	
	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
	public static String post(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("urlencoded-form", "application/x-www-form-urlencoded");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    

	
	/**
	 * 获取重定向地址
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	private static String getRedirectUrl(String url) throws Exception {
		// 发送get请求
		URL serverUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
		conn.setRequestMethod("GET");
		// 必须设置false，否则会自动redirect到重定向后的地址
		conn.setInstanceFollowRedirects(false);
//		conn.addRequestProperty("Cookie", "PHPSESSID=pe0pd6mfmui9s8q5n7i89ns3d1; UM_distinctid=1612d83351d607-0fa8b9608242b6-324a7a55-1fa400-1612d83351e465; kt_referer=https%3A%2F%2F7700327.com%2F; kt_qparams=2022cm4; 2022dows=1; 2022return=1; a0778_pages=3; a0778_times=2; __tins__19290778=%7B%22sid%22%3A%201516930291489%2C%20%22vd%22%3A%203%2C%20%22expires%22%3A%201516932098536%7D; a2699_pages=3; a2699_times=2; __tins__19332699=%7B%22sid%22%3A1516930291495%2C%22vd%22%3A3%2C%22expires%22%3A1516932098540%7D; __51cke__=; __51laig__=65; CNZZDATA1270565816=547262410-1516885244-https%253A%252F%252F7700327.com%252F%7C1516925121; CNZZDATA1271527842=270376172-1516882263-https%253A%252F%252F7700327.com%252F%7C1516925683; kt_tcookie=1; kt_is_visited=1; 2022user=1; kt_ips=111.19.35.22%2C111.19.41.224");
		conn.addRequestProperty("Accept", "*/*");
		conn.addRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
		conn.addRequestProperty("X-Requested-With", "ShockwaveFlash/21.9.9.999");
		conn.addRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36 Core/1.47.933.400 QQBrowser/9.4.8699.400");
//		conn.addRequestProperty("Referer", "https://www.2022cm2.com/videos/516/53d38f2e8cc445020778cabebe24322d/");
		conn.connect();
		// 判定是否会进行302重定向
		if (conn.getResponseCode() == 302 || conn.getResponseCode() == 301) {
			System.out.println("302");
			// 如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
			String location = conn.getHeaderField("Location");
			String cookies = conn.getHeaderField("Set-Cookie");
			serverUrl = new URL(location);
			conn = (HttpURLConnection) serverUrl.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Cookie", cookies);
			conn.addRequestProperty("Accept-Charset", "UTF-8;");
			conn.addRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
			conn.addRequestProperty("Referer", url);
			conn.connect();
			if (location != null && location.startsWith("http")) {
				System.out.println(location);
				return location;
			} else {
				return "";
			}
		} else {
			System.out.println(conn.getResponseCode());
			// 将返回的输入流转换成字符串
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			String html = buffer.toString();
			Pattern pattern = Pattern.compile("video=\\[(.*mp4)\\'");
			Matcher matcher = pattern.matcher(html);
			if (matcher.find()) {
				String link = matcher.group(1);
				link = link.replaceFirst("'", "/");
				String prefix = url.substring(0, url.lastIndexOf("/"));
				System.out.println(prefix + link);
			}
			return buffer.toString();
		}
	}
}
